package com.sx.controller;

import com.sx.dao.OptionRecordDao;
import com.sx.pojo.*;
import com.sx.pojo.Category;
import com.sx.pojo.Goods;
import com.sx.pojo.Supplier;
import com.sx.service.GoodService;
import com.sx.service.OptionRecordService;
import com.sx.service.SupplierService;
import com.sx.service.serviceImpl.GoodServiceImpl;
import com.sx.service.serviceImpl.OptionRecordServiceImpl;
import com.sx.service.serviceImpl.SupplierServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

@WebServlet("/good.action")
public class GoodServlet extends HttpServlet {
    // TODO: 2024/3/31
    @Serial
    private static final long serialVersionUID = 1L;
    private final GoodService goodService = new GoodServiceImpl();
    private final SupplierService supplierService = new SupplierServiceImpl();
    private final Logger logger = LogManager.getLogger(GoodServlet.class);
    private final OptionRecordService optionRecordService = new OptionRecordServiceImpl();

    /**
     * 处理HTTP GET请求
     * 此方法根据请求参数执行不同的操作当参数action为"list"时，它会从数据库中获取所有商品信息，
     * 并将这些信息传递给页面进行显示
     *
     * @param req  包含请求数据的HttpServletRequest对象
     * @param resp 用于发送响应数据的HttpServletResponse对象
     * @throws ServletException 如果Servlet遇到异常
     * @throws IOException      如果发生输入或输出异常
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");
        // 设置响应内容类型
        resp.setContentType("text/html;charset=UTF-8");
        // 获取请求参数
        String action = req.getParameter("action");
        //获取session
        HttpSession session = req.getSession();
        Person user = null;
        if (session.getAttribute("person") == null) {
            // 重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        } else {
            user = (Person) session.getAttribute("person");
        }
        switch (action) {
            case "list" -> {
                // 调用服务获取所有商品信息
                ArrayList<Goods> goods = goodService.getAllGoods();
                // 将商品信息存储在请求范围内
                req.setAttribute("goodsList", goods);
                // 设置主页面的右侧内容页面
                req.setAttribute("mainRight", "/jsp/goodList.jsp");
                // 转发请求到主页面
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            }
            case "add" -> {
                // 调用服务获取所有供应商信息
                ArrayList<Category> allCategory = supplierService.getAllCategory();
                ArrayList<Supplier> allSupplier = supplierService.getAllSupplier();
                req.setAttribute("supplierList", allSupplier);
                // 调用服务获取所有商品分类信息
                req.setAttribute("categoryList", allCategory);
                // 设置主页面的右侧内容页面
                req.setAttribute("mainRight", "/jsp/addGood.jsp");
                // 转发请求到主页面
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            }
            case "update" -> {
                String id = req.getParameter("id");
                if (id != null && !id.isEmpty()) {
                    // 调用服务获取指定商品信息
                    Goods good = goodService.getGoodById(id);
                    if (good != null) {
                        // 调用服务获取所有供应商信息
                        ArrayList<Category> allCategory = supplierService.getAllCategory();
                        ArrayList<Supplier> allSupplier = supplierService.getAllSupplier();
                        req.setAttribute("supplierList", allSupplier);
                        // 调用服务获取所有商品分类信息
                        req.setAttribute("categoryList", allCategory);
                        // 将商品信息存储在请求范围内
                        req.setAttribute("goods", good);
                        // 设置主页面的右侧内容页面
                        req.setAttribute("mainRight", "/jsp/updateGood.jsp");
                        req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
                    } else {
                        req.setAttribute("errorMsg", "商品不存在");
                    }
                } else {
                    req.setAttribute("errorMsg", "商品不存在");
                }
            }
            case "delete" -> {
                //  删除信息操作
                // 设置响应内容类型为 JSON
                String id = req.getParameter("id");
                resp.setContentType("application/json;charset=UTF-8");
                PrintWriter out = resp.getWriter();
                if (id == null) {
                    out.print("{\"status\":\"error\",\"message\":\"删除失败，请选择要删除的数据。\"}");
                } else {
                    try {
                        // 这里假设你会调用相应的服务层方法进行人员删除操作
                        // 例如：PersonService.deletePerson(id);
                        // 这里为了示例，模拟删除操作成功或失败
                        //添加操作记录
                        //删除的操作flag为3
                        //操作的商品表type为1
                        boolean success = goodService.deleteGoodById(user.getId(), user.getName(), 3, id, 1);
                        if (success) {
                            //optionRecordService.addOptionRecord(user.getId(), user.getName(), 3, id,1);
                            // 删除成功，返回成功信息
                            out.print("{\"status\":\"success\",\"message\":\"删除成功\"}");
                            // resp.sendRedirect("/person.action?action=list");
                        } else {
                            // 删除失败，返回失败信息和原因
                            out.print("{\"status\":\"error\",\"message\":\"删除失败，可能是因为关联数据存在，请先处理关联数据。\"}");
                        }
                    } catch (Exception e) {
                        // 异常处理，返回错误信息
                        out.print("{\"status\":\"error\",\"message\":\"删除操作发生异常，请稍后重试。\"}");
                    }

                }
            }
            case "stockQuery" -> {
                req.setAttribute("mainRight", "/jsp/inventoryQuery.jsp");
                // 转发请求到index.jsp页面
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            }
            case "recordQuery" -> {
                ArrayList<GoodsOpRecords> goodsOpRecords = goodService.getAllGoodRecords();
                req.setAttribute("goodsOpRecords", goodsOpRecords);
                req.setAttribute("mainRight", "/jsp/goodRecordList.jsp");
                // 转发请求到index.jsp页面
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");
        // 设置响应内容类型
        resp.setContentType("text/html;charset=UTF-8");
        String action = req.getParameter("action");
        //获取session
        HttpSession session = req.getSession();
        Person user = null;
        if (session.getAttribute("person") == null) {
            // 重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/login");
            return;
        } else {
            user = (Person) session.getAttribute("person");
        }
        switch (action) {
            case "save" -> {
                // 从请求参数中获取数据
                String id = req.getParameter("id");
                String categoryId = req.getParameter("categoryId");
                String name = req.getParameter("name");
                float price = Float.parseFloat(req.getParameter("price"));
                String description = req.getParameter("description");
                float inPrice = Float.parseFloat(req.getParameter("inPrice"));
                Integer number = Integer.parseInt(req.getParameter("number"));
                String createDateStr = req.getParameter("createDate");
                Integer shelfLife = Integer.parseInt(req.getParameter("shelfLife"));
                String supplierId = req.getParameter("supplier_id");

                // 将字符串日期转换为Date对象
                Date createDate = Date.valueOf(createDateStr);
                // 创建Goods对象
                Goods goods = new Goods(id, categoryId, name, price, description, inPrice, number, createDate, shelfLife, supplierId);
                // boolean isSaved = goodService.saveGood(goods);
                boolean isSaved = goodService.saveGood(goods, user.getId(), user.getName(), 1, 1, id);
                if (isSaved) {
                    logger.info("保存成功");
                    resp.getWriter().write("保存成功");
                } else {
                    logger.info("保存失败");
                    resp.getWriter().write("保存失败");
                }

            }
            case "update" -> {
                resp.setContentType("text/html;charset=UTF-8");
                // 从请求参数中获取数据
                String id = req.getParameter("id");
                String categoryId = req.getParameter("categoryId");
                String name = req.getParameter("name");
                float price = Float.parseFloat(req.getParameter("price"));
                String description = req.getParameter("description");
                float inPrice = Float.parseFloat(req.getParameter("inPrice"));
                Integer number = Integer.parseInt(req.getParameter("number"));
                String createDateStr = req.getParameter("createDate");
                Integer shelfLife = Integer.parseInt(req.getParameter("shelfLife"));
                String supplierId = req.getParameter("supplier_id");

                // 将字符串日期转换为Date对象
                Date createDate = Date.valueOf(createDateStr);
                // 创建Goods对象
                Goods goods = new Goods(id, categoryId, name, price, description, inPrice, number, createDate, shelfLife, supplierId);
                boolean isUpdated;
                //isUpdated = goodService.updateGood(goods);
                isUpdated = goodService.updateGood(goods, user.getId(), user.getName(), 2, 1, id);
                if (isUpdated) {
                    resp.getWriter().write("修改成功");
                } else {
                    resp.getWriter().write("修改失败");
                }
            }
            case "stockQuery" -> {
                ArrayList<GoodsStock> goodsStocks = goodService.findByName(req.getParameter("name"));
                req.setAttribute("goodsStocks", goodsStocks);
                req.setAttribute("mainRight", "/jsp/inventoryQuery.jsp");
                // 转发请求到index.jsp页面
                req.getRequestDispatcher("/jsp/index.jsp").forward(req, resp);
            }
        }


    }
}
